<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 支付类
 * @package  htdocs
 * @author   allen.qiang
 * @version 1.0
 */

class quanliOnlinepay {

    private $gateUrl;   //网关地址

    private $parameters;//请求参数

    /**
     *
     * 接收在线支付返回参数
     *
     */
    public function receiveParameter() {
        if (!empty($_REQUEST)) {
            $this->setParamsArray($_REQUEST);
        }
    }

    /**
     * 根据键值和值保存参数
     * @param string $key
     * @param string $value
     */
    public function setParameter($key, $value) {
        $this->parameters[$key] = $value;
    }

    /**
     * 保存参数
     * @param array $paramsArray
     */
    public function setParamsArray( $paramsArray ) {
        foreach($paramsArray as $k => $v) {
            $this->setParameter( $k, $v );
        }
    }

    /**
     * 根据key获得参数数值
     * @param string $key
     * @return mixed
     */
    public function getParameter( $key ) {
        if (isset($this->parameters[$key])) {
            return $this->parameters[$key];
        } else {
            return null;
        }
    }

    /**
     * 获取所有参数
     * @return array
     */
    public function getAllParameters() {
        return $this->parameters;
    }

    /**
     * 设置网关地址
     * @param string $gateUrl
     */
    public function setGateURL( $gateUrl ) {
        $this->gateUrl = $gateUrl;
    }

    /**
     * 生成签名字符串
     * @param array $filter 要过滤的字符串数据
     * @param int $is_sort 是否排序
     * @return string
     */
    public function createSignStr( $filter = array(), $is_sort = 1 ) {

        //得到所有参数，并排序
        $params = $this->getAllParameters();
        if ($is_sort) {
            ksort( $params );
        }

        $sign_str = '';
        foreach($params as $k => &$v) {
            if (in_array($k, $filter)) {
                continue;
            }
            if ($sign_str == '') {
                $sign_str .= $k . '=' . $v;
            } else {
                $sign_str .= '&' . $k . '=' . $v;
            }
        }

        return $sign_str;

    }

    /**
     * 生成请求链接
     * @return string
     */
    public function createRequestUrl() {
        return $this->gateUrl . '?' . http_build_query( $this->getAllParameters() );
    }

    /**
     * 生成请求表单
     */
    public function createRequestForm( $filter_array = array() ) {

        $params = $this->getAllParameters();
        $formHtml = '<form action="' . $this->gateUrl . '" method="post" target="_blank" id="pay_form" style="display: none;">';
        foreach($params as $k => $v) {
            if (in_array($k, $filter_array)) {
                continue;
            }
            $formHtml .= '<input type="hidden" value="' . $v . '" name="' . $k . '">';
        }
        $formHtml .= '</form>';

        return $formHtml;

    }

    /**
     * 保存订单支付异常信息
     * @param int $bill_no 订单号
     * @param int $payTypeID 支付方式ID
     * @param string $remark 异常备注
     */
    private function savePayException($bill_no, $payTypeID, $remark) {

        global $G_SHOP;

        $exception_obj = new entity('log_onlinepay_bill_exception');
        $exception_obj->bill_no = $bill_no;
        if (!$G_SHOP->DBCA->fetch($exception_obj)) {
            $exception_obj->creator = 'system_pay';
        }
        $exception_obj->payTypeID = $payTypeID;
        $exception_obj->remark = $remark;
        $G_SHOP->DBCA->save($exception_obj);

    }

    /**
     * 普通订单支付
     * @param array $arg_array
     * @return bool
     */
    public function billPay( $arg_array ) {

        global $G_SHOP;

        quanli_include('module/base/common/quanliLog.class.php');

        //实例日志类
        $quanliLog = new quanliLog();

        try {
             //add by 20141121 allen.qiangFUN-AC-0018-会员部感恩节活动 start
            $this->use_Integral($arg_array);
            //add by 20141121 allen.qiangFUN-AC-0018-会员部感恩节活动 end

             ///add 20141222 diandong.cao FUN-AC-0031-BD圣诞节 start
            $this->bd_christmas($arg_array);
            //add 20141222 diandong.cao FUN-AC-0031-BD圣诞节 end

            //查询订单
            $bill_obj = new entity('bill_master');
            $bill_obj->bill_no = $arg_array['bill_no'];
            $bill_obj->pcustID = $arg_array['pcustID'];
            if (!$G_SHOP->DBCA->fetch($bill_obj)) {
                throw new Exception('订单数据没有找到', 404);
            }
            if (in_array($bill_obj->bill_status, array(1, 2, 3, 4, 5, 6, 7))) {
                throw new Exception('订单已审核', 404);
            }
            if ($bill_obj->bill_status == 10) {
                throw new Exception('订单已取消', 404);
            }
            if ($bill_obj->pay_status == 1) {
                throw new Exception('订单已付款', 404);
            }
            $bill_obj->pay_status = 1;
            $bill_obj->payed_time = $G_SHOP->sys_datetime;
            $bill_obj->bill_online_money = $bill_obj->bill_receivable_money;
            $bill_obj->bill_received_money += $bill_obj->bill_receivable_money;
            $bill_obj->bill_receivable_money = 0;

            //查询订单支付
            $bill_pay_obj =  new entity('bill_pay');
            $bill_pay_obj->bill_no = $arg_array['bill_no'];
            $bill_pay_obj->payTypeID = $arg_array['payTypeID'];
            if (!$G_SHOP->DBCA->fetch($bill_pay_obj)) {
                throw new Exception('订单支付数据没有找到', 404);
            }

            //检查支付金额
            $total = round($arg_array['total_amount'] - $bill_pay_obj->pay_amount, 2);
            if ($total < 0) {
                throw new Exception('支付的金额小于应付金额', 404);
            }

            $bill_pay_obj->deduct_amount = $bill_pay_obj->pay_amount;
            $bill_pay_obj->paid_confirm_status = 1;
            $bill_pay_obj->paid_confirmer = 'system_pay';
            $bill_pay_obj->paid_confirm_time = $G_SHOP->sys_datetime;
            $bill_pay_obj->pay_time = $G_SHOP->sys_datetime;
            $bill_pay_obj->pay_code = $arg_array['pay_code'];


            //添加订单轨迹
            $bill_trace_obj = new entity('bill_trace');
            $bill_trace_obj->creator = 'system';
            $bill_trace_obj->bill_no = $arg_array['bill_no'];
            $bill_trace_obj->content = '您的订单已付款';

            $arg_log_array = array(
                '订单已付款：',
                '　　支付时间：' . $G_SHOP->sys_datetime,
                '　　支付流水：' . $bill_pay_obj->bill_pay_no,
                '　　支付金额：' . $bill_pay_obj->pay_amount,
                '　　支付方式：' . $bill_pay_obj->payTypeName . '(在线支付)',
            );

            //保存日志
            $log_array = array(
                'logCategoryID' => 1,
                'logItem' => $arg_array['bill_no'],
                'extend_1' => implode('<br>', $arg_log_array),
                'extend_5' => 0,
                'operator' => 'system'
            );

        } catch (Exception $e) {

            $this->savePayException($arg_array['bill_no'], $arg_array['payTypeID'], $e->getMessage() );
            return false;

        }

        try {

            $G_SHOP->DBCA->beginTransaction();

            $G_SHOP->DBCA->save($bill_obj);
            $G_SHOP->DBCA->save($bill_pay_obj);
            $G_SHOP->DBCA->save($bill_trace_obj);
            $quanliLog->saveLogInfo( $log_array );

            $G_SHOP->DBCA->commit();

        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            $msg =  $e->getMessage();
            if ( $msg == 'Deadlock found when trying to get lock; try restarting transaction' ) {
                $arr = $G_SHOP->DBCA->stmt_query('SHOW ENGINE INNODB STATUS');
                if ($arr) {
                    $arr = $arr[0];
                    $msg .= $arr->Status;
                }
            }
            $this->savePayException($arg_array['bill_no'], $arg_array['payTypeID'],$msg );
            return false;

        }

        return true;

    }

    /**
     * 保存在线支付请求参数
     * @param int $bill_no 订单号
     * @param int $payTypeID 支付方式ID
     * @param string $payTypeName 支付方式名称
     * @return int
     */
    public function setSendParams($bill_no, $payTypeID, $payTypeName) {

        //mod sunqiang 2015-03-20 MK-OT-1005 MYSQL慢日志处理 start

//        global $G_SHOP;
//
//        //查询在线支付日志信息
//        $log_obj = new entity('log_onlinepay');
//        $log_obj->bill_no = $bill_no;
//        if (!$G_SHOP->DBCA->fetch($log_obj)) {
//            $log_obj->creator = 'system_onlinepay';
//            $log_obj->request_flg = 1;
//        } else {
//            if ($log_obj->request_flg == 3) {
//                return 0;
//            }
//        }
//        $log_obj->request_str = print_r($this->getAllParameters(), true);
//        $log_obj->beginTime = $G_SHOP->sys_datetime;
//        $log_obj->payTypeID = $payTypeID;
//        $log_obj->payTypeName = $payTypeName;
//        $G_SHOP->DBCA->save( $log_obj );
//
//        return 1;


        global $G_SHOP;

        //查询在线支付日志信息
        $log_obj = new entity('log_onlinepay');
        $log_obj->bill_no = $bill_no;
        if (!$G_SHOP->DBCA->fetch($log_obj)) {
            $log_obj->creator = 'system_onlinepay';
            $log_obj->request_flg = 1;
            $log_obj->request_str = print_r($this->getAllParameters(), true);
            $log_obj->beginTime = $G_SHOP->sys_datetime;
            $log_obj->payTypeID = $payTypeID;
            $log_obj->payTypeName = $payTypeName;
            $G_SHOP->DBCA->save( $log_obj );

        } else {
            if ($log_obj->request_flg == 3) {
                return 0;
            }

            $sql = "UPDATE log_onlinepay SET request_str = ?,beginTime = ?,payTypeID = ?,payTypeName = ? WHERE bill_no = ? ";
            $G_SHOP->DBCA->stmt_query( $sql , "ssisi" , array( print_r($this->getAllParameters(), true) , $G_SHOP->sys_datetime , $payTypeID , $payTypeName , $bill_no ) );
        }

        return 1;

        //mod sunqiang 2015-03-20 MK-OT-1005 MYSQL慢日志处理 end
    }


    /**
     * 保存在线支付服务端和客户端返回的数据
     * @param int $bill_no 订单号
     * @param int $responseType 1：服务端返回 2：客户端返回
     * @param int $request_flg 支付状态 2:失败 3：成功
     * @return int
     */
    public function setReceiveParams( $bill_no, $responseType, $request_flg=3 ) {

        //mod sunqiang 2015-03-20 MK-OT-1005 MYSQL慢日志处理 start
//        global $G_SHOP;
//
//        $return_flg = 1;
//
//        $log_obj = new entity('log_onlinepay');
//        $log_obj->bill_no = $bill_no;
//        if ($G_SHOP->DBCA->fetch($log_obj)) {
//            if ($responseType == 1) {
//                if ($log_obj->request_flg == 3) {
//                    $return_flg = -1;
//                }
//                $log_obj->endTime = $G_SHOP->sys_datetime;
//                $log_obj->server_response_str = print_r( $this->getAllParameters(), true);
//                $log_obj->request_flg = $request_flg;
//                $log_obj->success_count += 1;
//            } else {
//                $log_obj->client_response_str = print_r( $this->getAllParameters(), true);
//            }
//            $G_SHOP->DBCA->save( $log_obj );
//        }
//
//        return $return_flg;



        global $G_SHOP;

        $return_flg = 1;
        //参数类型字符串
        $params_type = '';
        //参数值数组
        $params_array = array();

        $log_obj = new entity('log_onlinepay');
        $log_obj->bill_no = $bill_no;
        if ($G_SHOP->DBCA->fetch($log_obj)) {
            if ($responseType == 1) {
                if ($log_obj->request_flg == 3) {
                    $return_flg = -1;
                }

                $sql = "UPDATE log_onlinepay SET endTime = ?,server_response_str = ?,request_flg = ?,success_count = success_count+1 WHERE bill_no = ? ";
                $params_type = 'ssii';
                $params_array = array($G_SHOP->sys_datetime,print_r( $this->getAllParameters(), true),$request_flg,$bill_no);

            } else {
                $sql = "UPDATE log_onlinepay SET client_response_str = ? WHERE bill_no = ? ";
                $params_type = 'si';
                $params_array = array(print_r( $this->getAllParameters(), true),$bill_no);

            }
            $G_SHOP->DBCA->stmt_query( $sql , $params_type , $params_array );
        }

        return $return_flg;

        //mod sunqiang 2015-03-20 MK-OT-1005 MYSQL慢日志处理 end


    }

    /**
     * 支付控制器，根本不同订单类型调用不同订单支付
     * @param array $arg_array
     */
    public function payAction( $arg_array ) {

        if ($arg_array['billType'] == 1) {

            //更新订单支付信息
            $this->billPay( $arg_array );

        }

    }

    /*
   *  使用感恩节优惠券送积分
   *  @package ajax
   *  @backend  shop
   *  @author   allen.qiang <allen.qiang@fistforward.com>
   *  20141121 add by 曹佃FUN-AC-0018-会员部感恩节活动
   *  $reust 订单提交数组
   */
    function use_Integral($reust){
        global $G_SHOP;
        quanli_require('module/base/activity/activityConfig.class.php');//活动配置文件
        $activity_config = new activityConfig('Thanksgiving'); //活动配置
        $config_array = $activity_config->config;
        $couponID=$config_array['couponID'];
        quanli_require('module/func/eai.func.php');
        //实例crm类
        $crm_obj_cdd = eai_crm();

        //查询该订单使用的优惠券
        $use_coupon="SELECT count(1) as num FROM  bill_use_coupon where bill_no=? and  couponID in (".$couponID.") ";
        $use_coupon_query=$G_SHOP->DBCA->stmt_query($use_coupon,'s',$reust['bill_no']);
        if( $use_coupon_query[0]->num){

            //积分日志记录
            $integral_log=new entity('integral_log');
            $integral_log->pcustID=$reust['pcustID'];
            $integral_log->logType='2';//感恩节积分日志类型
            $integral_log->logName='感恩节优惠券下单送500积分';
            $integral_log->logValue='500';
            $G_SHOP->DBCA->save($integral_log);//修改光棍节日志表
            //积分账户充值
            $arg_array = array(
                'pcustID' => $reust['pcustID'],   //会员ID
                'subjectId' => G_POINTS_ID,              //积分常量
                'amount' => 500,                            //积分数量
                'operator' => 'system',
                'remark' => '感恩节优惠券下单送500积分'
            );
            $crm_obj_cdd->recharge( $arg_array );


        }

    }
    /*
    *  BD圣诞节
    *  @package ajax
    *  @backend  shop
    *  @author   allen.qiang <allen.qiang@fistforward.com>
    *  20141222 add by 曹佃FUN-AC-0031-BD圣诞节
    *  $reust 订单提交数组
    */
    function bd_christmas($reust){
        global $G_SHOP;
        //error_log(print_r($reust,1));
        //error_log(print_r('-----------',1));
        quanli_require('module/base/activity/activityConfig.class.php');//活动配置文件
        $activity_config = new activityConfig('christmas_cake'); //活动配置
        $config_array = $activity_config->config;
        $configID=$config_array['configID'];
        //error_log(print_r($configID,1));
        //error_log(print_r('-----------',1));

        $bill_sql="select count(1) as bill_sum from bill_master where bill_no=? and  billPromotion=?";
        $bill_query=$G_SHOP->DBCA->stmt_query($bill_sql,'ss',$reust['bill_no'],$configID);
        //error_log(print_r($bill_query[0]->bill_sum,1));
        //error_log(print_r('-----------',1));

        if($bill_query[0]->bill_sum){
            $activity_extend=new entity("activities_extend");
            $activity_extend->activityNumber=66000;
            $activity_extend->extend_1=$reust['pcustID'];
            $activity_extend->extend_6=$reust['bill_no'];
            $activity_extend->extend_7=0;
            $zc=$G_SHOP->DBCA->save($activity_extend);
            //error_log(print_r($zc,1));
        }

    }

}